<?php
namespace app\controller;
use tools\Code;
use tools\Model;

class UserController extends CommonController {


//    加载登录页面
    public function login(){
        if(IS_POST){
            if(strtolower($_POST['code'])!=strtolower($_SESSION['code'])){
                $this->redirect('?c=user&a=login','验证码不正确');

            }
            $users = (new Model())->query('select * from users');
            foreach($users as $v){
                if($_POST['username']==$v['username']){
                    if(password_verify($_POST['password'],$v['password'])){
                        if(!empty($_POST['auto'])){
//                            session_save_path('./sessions');
                            setcookie(session_name(),session_id(),time()+3600*24*7,'/');
                        }
                        $_SESSION['username']=$_POST['username'];
//                        var_dump($_SESSION['username']);
                        $this->redirect('index.php','登录成功');
                    }
                }
            }
            $this->redirect('?c=user&a=login','用户名或密码不正确');
        }
        include 'view/login.html';
    }
//    加载注册页面
    public function register(){
        if(IS_POST){
            if(strtolower($_POST['code'])!=strtolower($_SESSION['code'])){
                $this->redirect('?c=user&a=register','验证码不正确');
            }
            $password=password_hash($_POST['password'],PASSWORD_DEFAULT);
            (new Model())->exec("insert into users (username,password) values ('{$_POST['username']}','{$password}')");
            $this->redirect('?c=user&a=login','注册成功');
        }

        include 'view/register.html';
    }
//    加载验证码
    public function code(){
        (new Code(1,100,30))->show();
    }
//    退出登录
    public function logout(){
        session_unset();
        setcookie(session_name(),session_id(),time()-3600*24*7,'/');
        session_destroy();
        header('location:index.php');
    }
}